<template>
  <!-- directorys.vue 专用组件 -->
  <div class="container">
    <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancel"
      width="27%">
      <!-- 表单 -->
      <el-form ref="direForm" :model="addData" :rules="rules">
        <el-form-item label="所属学科" prop="subjectID">
          <el-select style="width:60%" v-model="addData.subjectID">
            <el-option v-for="item in direList" :key="item.value"
              :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input style="width:60%" placeholder="请输入目录名称"
            v-model="addData.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template #footer>
        <el-row type="flex" justify="center">
          <el-col>
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button type="primary" size="small" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 接受父组件传递数据
    addData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      // 调用简单列表时，接收列表数据
      direList: [],
      rules: {
        subjectID: [
          { required: true, message: '学科名称不能为空', trigger: 'change' }
        ],
        directoryName: [
          { required: true, message: '目录名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 弹层标题判断
    showTitle () {
      return this.addData.id ? '修改目录' : '新增目录'
    }
  },
  created () {
    this.getSimpleList()
  },
  methods: {
    // 获取简单列表用于弹层学科名称渲染
    async getSimpleList () {
      const { data } = await simple()
      this.direList = data
      console.log(this.direList)
    },
    btnCancel () {
      this.$emit('update:showDialog', false)
      this.$refs.direForm.resetFields()
      this.$parent.addData.id = ''
      this.$parent.addData = {}
    },
    // query () {
    //   this.addData = {}
    // },
    async btnOK () {
      // this.query()
      try {
        // console.log(222)

        await this.$refs.direForm.validate()
        if (this.addData.id) {
          // 修改
          await update(this.addData)
          await this.$message.success('修改成功')
        } else {
          // 新增
          // this.addData.directoryName = ''
          // this.addData.subjectID = ''
          // console.log(111)
          await add(this.addData)
          this.$message.success('添加成功')
        }

        await this.$parent.list()
        this.$parent.showDialog = false
        this.$parent.addData.id = ''
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang='scss'></style>
